<template>
  <div class="supplier-detail-page">
    <!-- 页面标题和操作区 -->
    <!-- <el-page-header :content="$route.meta.title || '供应商基础信息'">
      <template #extra>
        <el-button type="primary" @click="handleEdit" :icon="editMode ? EditPen : Edit">
          {{ editMode ? '保存' : '编辑' }}
        </el-button>
      </template>
    </el-page-header> -->

    <!-- 标签页容器 -->
    <el-tabs v-model="activeTab" class="mt-4">
      <el-tab-pane label="基本信息" name="baseInfo">
        <!-- 基础信息区块 -->
        <el-card class="mb-4">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <span>基础信息</span>
              <el-button v-if="activeTab === 'baseInfo'" type="primary" @click="handleEdit">
                {{ editMode ? '保存' : '编辑' }}
              </el-button>
            </div>
          </template>

          <el-form
            ref="baseInfoForm"
            :model="supplierInfo"
            :rules="baseInfoRules"
            label-width="120px"
            class="mt-4"
          >
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="供应商编码" prop="code">
                  <el-input v-model="supplierInfo.code" :disabled="true" placeholder="自动生成" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="供应商名称" prop="name">
                  <el-input
                    v-model="supplierInfo.name"
                    :disabled="!editMode"
                    placeholder="请输入供应商名称"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="供应商分类" prop="supplierClassCode">
                  <el-select
                    v-model="supplierInfo.supplierClassCode"
                    :disabled="!editMode"
                    placeholder="请选择供应商分类"
                  >
                    <el-option
                      v-for="item in supplierClassList"
                      :key="item.code"
                      :label="item.type"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="经营范围" prop="range">
                  <el-input
                    v-model="supplierInfo.range"
                    :disabled="!editMode"
                    placeholder="请输入经营范围"
                    type="textarea"
                    rows="2"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="公司规模" prop="scale">
                  <el-input
                    v-model="supplierInfo.scale"
                    :disabled="!editMode"
                    placeholder="请输入公司规模"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="公司邮编" prop="postal">
                  <el-input
                    v-model="supplierInfo.postal"
                    :disabled="!editMode"
                    placeholder="请输入公司邮编"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="公司电话" prop="phone">
                  <el-input
                    v-model="supplierInfo.phone"
                    :disabled="!editMode"
                    placeholder="请输入公司电话"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="公司传真" prop="fax">
                  <el-input
                    v-model="supplierInfo.fax"
                    :disabled="!editMode"
                    placeholder="请输入公司传真"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="公司网站" prop="website">
                  <el-input
                    v-model="supplierInfo.website"
                    :disabled="!editMode"
                    placeholder="请输入公司网站"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="国家地区" prop="country">
                  <el-input
                    v-model="supplierInfo.country"
                    :disabled="!editMode"
                    placeholder="请输入国家地区"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="所在时区" prop="timeZone">
                  <el-input
                    v-model="supplierInfo.timeZone"
                    :disabled="!editMode"
                    placeholder="请输入所在时区"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="所在城市" prop="city">
                  <el-input
                    v-model="supplierInfo.city"
                    :disabled="!editMode"
                    placeholder="请输入所在城市"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="港口" prop="harbor">
                  <el-input
                    v-model="supplierInfo.harbor"
                    :disabled="!editMode"
                    placeholder="请输入港口"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="常住地址" prop="addressPermanent">
                  <el-input
                    v-model="supplierInfo.addressPermanent"
                    :disabled="!editMode"
                    placeholder="请输入常住地址"
                    type="textarea"
                    rows="2"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="邮寄地址" prop="addressMail">
                  <el-input
                    v-model="supplierInfo.addressMail"
                    :disabled="!editMode"
                    placeholder="请输入邮寄地址"
                    type="textarea"
                    rows="2"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 联系人区块 -->
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>联系人</span>
              <div class="card-actions">
                <el-button type="primary" size="small" @click="openAddContactDialog">
                  新增
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="deleteContacts"
                  :disabled="selectedContactIds.length === 0"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            :data="contacts"
            border
            class="mt-4"
            @selection-change="handleContactSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="姓名" show-overflow-tooltip />
            <el-table-column prop="sex" label="性别" show-overflow-tooltip />
            <el-table-column prop="position" label="职务" show-overflow-tooltip />
            <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
            <el-table-column prop="landline" label="座机" show-overflow-tooltip />
            <el-table-column prop="phone" label="移动电话" show-overflow-tooltip />
            <el-table-column prop="facebook" label="Facebook" show-overflow-tooltip />
            <el-table-column prop="ins" label="Ins" show-overflow-tooltip />
            <el-table-column prop="tiktok" label="TikTok" show-overflow-tooltip />
            <el-table-column prop="youtube" label="Youtube" show-overflow-tooltip />
            <el-table-column prop="linkedin" label="Linkedin" show-overflow-tooltip />
            <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          </el-table>
        </el-card>

        <!-- 其他信息区块 -->
        <el-card>
          <template #header>
            <div class="card-header">其他信息</div>
          </template>

          <el-form :model="supplierInfo" label-width="120px" class="mt-4">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="创建人">
                  <el-input v-model="supplierInfo.creator" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="10">
                <el-form-item label="创建时间">
                  <el-input v-model="formattedCreateTime" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 其他标签页 -->
      <el-tab-pane label="供货记录" name="supplyRecord">
        <SupplyRecord :supplier-id="supplierId" />
      </el-tab-pane>
      <el-tab-pane label="供应商产品" name="products">
        <Products :supplier-id="supplierId" />
      </el-tab-pane>
      <el-tab-pane label="账户信息" name="accountInfo">
        <div class="empty-tab">功能开发中...</div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增联系人弹窗 -->
    <el-dialog v-model="contactDialogVisible" title="新增联系人" :width="600">
      <el-form ref="contactForm" :model="currentContact" :rules="contactRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="currentContact.name" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="currentContact.sex" placeholder="请选择">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="未知" value="未知" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="职务" prop="position">
              <el-input v-model="currentContact.position" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="currentContact.email" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="座机" prop="landline">
              <el-input v-model="currentContact.landline" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="移动电话" prop="phone">
              <el-input v-model="currentContact.phone" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="Facebook">
              <el-input v-model="currentContact.facebook" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="Ins">
              <el-input v-model="currentContact.ins" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="TikTok">
              <el-input v-model="currentContact.tiktok" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="Youtube">
              <el-input v-model="currentContact.youtube" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="Linkedin">
              <el-input v-model="currentContact.linkedin" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="currentContact.remark" type="textarea" rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="contactDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveContact">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, toRefs, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Edit, EditPen, Plus, Delete } from '@element-plus/icons-vue'
import { SupplierInfoApi } from '@/api/busipart/supplierinfo/index'
import { SupplierContactsApi } from '@/api/busipart/suppliercontacts/index'
// import { getSupplierClassList } from '@/api/business/supplier-class';
import type { SupplierInfoVO } from '@/api/product/supplierinfo'
import SupplyRecord from '@/views/busipart/components/SupplyRecord.vue'
import { ElMessage } from 'element-plus'

import Products from '@/views/busipart/components/products.vue'

// 定义联系人类型
interface Contact {
  id?: number
  supplierId?: number
  name: string
  sex: string
  position: string
  email: string
  landline: string
  phone: string
  facebook: string
  ins: string
  tiktok: string
  youtube: string
  linkedin: string
  remark: string
}

// 页面状态
const activeTab = ref('baseInfo')
const editMode = ref(false)
const route = useRoute()
const supplierId = ref<number>(route.query.id as number)

// 表单数据
const supplierInfo = ref<SupplierInfoVO & { creator?: string; createTime?: string }>({
  id: 0,
  code: '',
  name: '',
  supplierClassCode: '',
  range: '',
  scale: '',
  postal: '',
  phone: '',
  fax: '',
  website: '',
  country: '',
  timeZone: '',
  city: '',
  harbor: '',
  addressPermanent: '',
  addressMail: '',
  sourceCode: '',
  industryCode: '',
  priorityCode: '',
  starCode: '',
  stageCode: '',
  statusCode: '',
  remark: '',
  creator: '', // 创建者
  createTime: '' // 创建时间
})

// 联系人数据
const contacts = ref<Contact[]>([])
const selectedContactIds = ref<number[]>([])
const contactDialogVisible = ref(false)
const currentContact = ref<Contact>({
  name: '',
  sex: '',
  position: '',
  email: '',
  landline: '',
  phone: '',
  facebook: '',
  ins: '',
  tiktok: '',
  youtube: '',
  linkedin: '',
  remark: ''
})

// 供应商分类列表
const supplierClassList = ref<any[]>([])

// 表单验证规则
const baseInfoRules = reactive({
  name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  // supplierClassCode: [{ required: true, message: '请选择供应商分类', trigger: 'change' }],
  supplierClassCode: [{ required: false, message: '请选择供应商分类', trigger: 'change' }],
  phone: [{ required: true, message: '请输入公司电话', trigger: 'blur' }]
})

const contactRules = reactive({
  name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职务', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入移动电话', trigger: 'blur' }]
})

// 生命周期 - 页面加载时获取数据
onMounted(async () => {
  // 打印所有路由参数
  console.log('路由参数:', route.query)
  console.log('供应商ID:', route.query.id)

  if (supplierId.value) {
    await fetchSupplierInfo()
    await fetchContacts()
  }
  await fetchSupplierClasses()
})

// 获取供应商信息
const fetchSupplierInfo = async () => {
  try {
    const response = await SupplierInfoApi.getSupplierInfo(supplierId.value)
    console.log('原始响应对象：', response)
    if (response.success) {
      console.log('获取到的供应商信息：', response)
      console.log('获取到的供应商信息：', response.data)
      supplierInfo.value = response.data
      console.log('supplierInfo after assignment供应商:', supplierInfo.value)
    } else {
      console.error('获取供应商信息失败，response.success 为 false:', response)
    }
  } catch (error) {
    console.error('获取供应商信息失败:', error)
  }
}

const formattedCreateTime = computed(() => {
  if (supplierInfo.value.createTime) {
    return new Date(supplierInfo.value.createTime).toLocaleString()
  }
  return ''
})

// 获取联系人列表
const fetchContacts = async () => {
  try {
    const response = await SupplierContactsApi.getSupplierContactsBySupplierId(supplierId.value)
    if (response.success) {
      contacts.value = response.data
    } else {
      console.log('response.success为false')
    }
  } catch (error) {
    console.error('获取联系人列表失败:', error)
  }
}

// 获取供应商分类
const fetchSupplierClasses = async () => {
  try {
    const response = await SupplierInfoApi.getSupplierClassList()
    if (response.success) {
      supplierClassList.value = response.data
    }
  } catch (error) {
    console.error('获取供应商分类失败:', error)
  }
}

// 编辑/保存按钮点击事件
const handleEdit = async () => {
  if (editMode.value) {
    // 保存逻辑
    try {
      // 调用更新接口
      await SupplierInfoApi.updateSupplierInfo(supplierInfo.value)
      editMode.value = false
      ElMessage.success('保存成功')
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  } else {
    // 进入编辑模式
    editMode.value = true
  }
}

// 打开新增联系人弹窗
const openAddContactDialog = () => {
  currentContact.value = {
    name: '',
    sex: '',
    position: '',
    email: '',
    landline: '',
    phone: '',
    facebook: '',
    ins: '',
    tiktok: '',
    youtube: '',
    linkedin: '',
    remark: ''
  }
  contactDialogVisible.value = true
}

// 保存联系人
const saveContact = async () => {
  try {
    // 创建要提交的数据对象
    const newContact = { ...currentContact.value, supplierId: supplierId.value }

    // 调用API新增联系人
    const response = await SupplierContactsApi.createSupplierContacts(newContact)

    // 检查响应结果
    if (response) {
      // 获取新增的联系人信息（如果API返回了完整信息）
      // 这里假设API成功返回后，我们重新获取联系人列表以确保数据同步
      await fetchContacts()

      // 关闭弹窗
      contactDialogVisible.value = false

      // 重置表单
      currentContact.value = {
        name: '',
        sex: '',
        position: '',
        email: '',
        landline: '',
        phone: '',
        facebook: '',
        ins: '',
        tiktok: '',
        youtube: '',
        linkedin: '',
        remark: ''
      }

      ElMessage.success('新增联系人成功')
    } else {
      ElMessage.error('新增联系人失败')
    }
  } catch (error) {
    console.error('新增联系人失败:', error)
    ElMessage.error('新增联系人失败: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 处理联系人选择变化
const handleContactSelectionChange = (selection: Contact[]) => {
  selectedContactIds.value = selection.map((item) => item.id!).filter(Boolean)
}

// 删除选中的联系人
const deleteContacts = async () => {
  try {
    // 调用删除接口逐个删除选中的联系人
    const deletePromises = selectedContactIds.value.map((id) =>
      SupplierContactsApi.deleteSupplierContacts(id)
    )

    await Promise.all(deletePromises)

    // 更新本地数据
    contacts.value = contacts.value.filter(
      (contact) => !selectedContactIds.value.includes(contact.id!)
    )
    selectedContactIds.value = []
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除联系人失败:', error)
    ElMessage.error('删除联系人失败')
  }
}

// 监听路由参数变化
watch(
  () => route.query,
  (newQuery) => {
    console.log('路由参数变化:', newQuery)
    console.log('当前供应商ID:', newQuery.id)
  },
  { immediate: true }
)
</script>

<style scoped>
.supplier-detail-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
  /* 添加纵向滚动条 */
  overflow-y: auto;
  /* 为了在内容超出视窗高度时显示滚动条 */
  max-height: calc(100vh - 64px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.empty-tab {
  text-align: center;
  padding: 50px 0;
  color: #999;
}
</style>
